Repository navigation
refactor(append-file)!: redesign rolling file appender with direct segment writes - #250
Merged
Merged
Conversation
…gment writes `RollingFileWriter` previously wrote to a single active file and shifted reverse-numbered archives (`.1 -> .2 -> .3`) via `fs::rename` on every rollover. That design performed `O(N)` filesystem renames under the writer mutex, risked sharing violations on Windows when external log collectors held open handles, opened new files without `O_APPEND`, panicked on filename suffix boundary underflows or out-of-range timestamps, truncated millisecond bounds to `usize` on 32-bit targets, and juggled multi-layer `Error` wrappers and stashed `Option<Error>` values across rotation and cleanup paths. Redesign `logforth-append-file` around direct-write segment files and flat, single-layer error propagation: - Write directly to segment files opened with `.append(true)` (`<stem>[.<suffix>]` without rotation, `<stem>.<period>[.<suffix>]` for time rotation, and `<stem>[.<period>].<seq>[.<suffix>]` with ascending `1..` sequence numbers when `rollover_size` is configured), eliminating `fs::rename` completely. - Check size bounds before writing (`size > 0 && size + len > max_size`) using `NonZeroU64` so segments stay within the configured byte budget while writing oversized single records whole into an empty segment. - Compute period bounds `[start, end)` in `jiff::Timestamp` across configurable `TimeZone` (`FileBuilder::timezone`, defaulting to the system timezone), reusing the active segment across repeated local hours during DST fall-back and avoiding panics or 32-bit truncation. - Validate filename stems and suffixes strictly and match only canonical regular segment files during retention cleanup, counting the active file toward `max_log_files` and never unlinking the active segment even if the wall clock steps backward. - Keep error handling linear and single-layer: if rollover or retention cleanup fails, throttle retries for one second, append the current record to the active segment, and return the underlying leaf `Error` directly. Signed-off-by: tison <wander4096@gmail.com>
Move historical release notes (`<= 0.30.1`) into `CHANGELOG-OLD.md` and organize `CHANGELOG.md` under `## Unreleased` using uniform, caller-facing `Breaking changes`, `New features`, `Improvements`, and `Bug fixes` entries covering all user-visible changes since `0.30.1`. Signed-off-by: tison <wander4096@gmail.com>
Standardize crate, type, and method documentation across `logforth-append-file` with consistent noun-phrase type summaries, present-tense method contracts, explicit default annotations, structured `# Errors` conditions on `FileBuilder::build`, and unified crate-level segment naming and retention sections. Signed-off-by: tison <wander4096@gmail.com>
…lock tests Move public-API behavior and regression tests into `appenders/file/tests/file_test.rs` so input validation, pre-write size boundaries (including trailing newline framing), retention ordering, non-matching entry preservation, append-after-truncation, and sequence exhaustion are exercised end-to-end through `FileBuilder` and `File`. Keep `src/` unit tests strictly for scenarios requiring private access (`Clock::ManualClock` in `rolling.rs` and `Rotation::period_at` in `rotation.rs`), asserting observable file and error outcomes rather than internal helper predicates. Signed-off-by: tison <wander4096@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
RollingFileWriterpreviously wrote to an unnumbered active file (app.log) and shifted reverse-numbered archives (.1 -> .2 -> .3) viafs::renameon every rollover. That design performedO(N)metadata and rename syscalls under the writer mutex, risked sharing violations on Windows when external log collectors held open handles withoutFILE_SHARE_DELETE, opened fresh files withoutO_APPEND(leaving NUL holes under externalcopytruncate), panicked on prefix/suffix boundary matches or extreme timestamps, truncated epoch milliseconds tousizeon 32-bit targets, and juggled nestedErrorwrappers and intermediateOption<Error>values across rollover and cleanup paths.This PR redesigns
logforth-append-filearound direct segment writes and straight-line, single-layer error propagation, and splits historical (<= 0.30.1) release notes intoCHANGELOG-OLD.mdwhile aligningCHANGELOG.mdunder## Unreleased.Rollover and Filename Layout Changes
With
FileBuilder::new(dir, "app").filename_suffix("log"):0.4.0)app.logapp.log(unchanged)app.log; rotatedapp.2026-11-25.1.log,.2.log(newest =1)app.2026-11-25.logapp.log; rotatedapp.1.log,app.2.log(newest =1)app.1.log,app.2.log, ... (oldest =1, newest = highest)app.log; rotatedapp.2026-11-25-17.1.log,.2.log(newest =1)app.2026-11-25-17.1.log,.2.log, ... (oldest =1, newest = highest)Concrete rollover and retention behavior when
rollover_sizeandmax_log_filesare configured:Upgrade note for existing log directories: files keep their initial segment name for their entire lifetime instead of being renamed on rollover. Files left behind by the previous layout (such as an unnumbered
app.logalongside rotated files,app.<date>.1.logunder time-only rotation, or reverse-numbered.1, .2archives where.1was newest) are either ignored by the stricter segment parser or ordered by ascending sequence number (1treated as oldest); move or remove old archives when upgrading in place if strict retention order across versions is required.API and Behavior Changes
FileBuilder::rollover_sizenow takesNonZeroU64instead ofNonZeroUsizeand rotates before a write would exceedmax_size(size > 0 && size + len > max_size) rather than after; a single oversized record written to an empty segment occupies that segment whole without extra empty files.FileBuilder::timezone(TimeZone)(andpub extern crate jiff) to configure the timezone used for rotation boundaries and period filenames, defaulting toTimeZone::system(). Repeated local hours during DST fall-back reuse the active segment until its second occurrence ends orrollover_sizeis reached.FileBuilder::max_log_filescounts the active file toward the total limit across all periods and never deletes the active file even if the system clock steps backward; startup cleanup runs on a best-effort basis so locked historical files do not failbuild().FileBuilder::buildvalidatesfilenameandfilename_suffixupfront, returningErrfor empty names,.or.., path separators, or NUL bytes, and matches only canonical regular files during retention scans..append(true)(O_APPEND), and keep runtime error propagation strictly single-layer: if rollover or retention cleanup fails, set a 1-second wall-clock-safe retry cooldown window, append the current record to the active segment, and return the leaflogforth_core::Errordirectly.